package org.example.finalsecurities.service;

import org.example.finalsecurities.entity.CrawlerLog;
import org.example.finalsecurities.entity.StockAlert;
import org.example.finalsecurities.mapper.AlertMapper;
import org.example.finalsecurities.utils.CrawlerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author : [Pashm]
 * @version : [v1.0]
 */
@Service
public class AlertService {
    private static final Logger log = LoggerFactory.getLogger(AlertService.class);
    @Autowired
    private AlertMapper alertMapper;
    @Autowired
    private CrawlerLogService crawlerLogService;

    public List<StockAlert> selectAll(){
        return alertMapper.selectAll();
    }

    public void insertOrUpdate(StockAlert stockAlert){
        StockAlert stockAlert1 = alertMapper.selectById(stockAlert.getId());
        if (stockAlert1 != null){
            stockAlert.setId(stockAlert1.getId());
            stockAlert.setCreateTime(stockAlert1.getCreateTime());
            alertMapper.updateById(stockAlert);
        }else {
            alertMapper.insert(stockAlert);
        }
    }

    public void fetchAndUpdateAlert(){
        Date startTime = new Date();
        log.info("开始爬取证券快讯数据:{}",startTime);
        //构建请求参数
        CrawlerLog crawlerLog = new CrawlerLog();
        crawlerLog.setActionDesc("爬取证券快讯");
        crawlerLog.setUrl("https://kuaixun.eastmoney.com");
        crawlerLog.setStartTime(startTime);
        //爬取数据
        List<StockAlert> stockAlerts = CrawlerUtil.crawlStockAlert();
        for(StockAlert stockAlert : stockAlerts){
            insertOrUpdate(stockAlert);
        }
        //保存爬取日志
        Date endTime = new Date();

        crawlerLog.setEndTime(endTime);
        crawlerLog.setCreateTime(endTime);
        crawlerLog.setUpdateTime(endTime);

        crawlerLogService.saveLog(crawlerLog);
        log.info("爬取证券快讯数据完成，本次爬虫日志: {}",crawlerLog);
    }
    public void delete(){
        alertMapper.delete();
    }

}
